package com.its.controller;

import com.its.domain.BaseResult;
import com.its.domain.CodeEnum;
import com.its.member.pojo.Member;
import com.its.pojo.MemberLoginResultDTO;
import com.its.service.MemberService;
import com.its.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;

import org.springframework.security.core.context.SecurityContextHolder;

import org.springframework.security.crypto.password.PasswordEncoder;

import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

import java.util.Collections;

@RestController
@RequestMapping("/Member")
public class MemberController {
    //注入业务层属性
    @Autowired
    private MemberService memberService;

    @Autowired
    private PasswordEncoder passwordEncoder;//注入密码加密工具

    //注入JWT工具
    @Autowired
    private JwtUtils jwtUtils;

    //声明单元方法：会员登录
    @PostMapping("/MemberLogin")
    public BaseResult<MemberLoginResultDTO> memberLogin(@RequestBody Member member){
        //1.根据会员账户查找数据库中的会员信息
        Member memberRes = memberService.selMemberByMemberCountService(member.getMemberAccount());

        //2.判断用户是否存在
        if(memberRes == null){
            return BaseResult.error(CodeEnum.LOGIN_NAME_PASSWORD_ERROR);
        }

        //3.适用SpringSecurity的passwordEncoder校验密码
        boolean matches = passwordEncoder.matches(member.getMemberPassword(), memberRes.getMemberPassword());

        if(!matches){
            return BaseResult.error(CodeEnum.LOGIN_NAME_PASSWORD_ERROR);
        }

        //4.登录成功，为了安全，清空密码字段
        memberRes.setMemberPassword(null);

        // 登录成功，生成 token
        String token = jwtUtils.createToken(String.valueOf(member.getMemberAccount()));

        // 登录成功后，构造一个认证对象（不依赖默认UserDetailsService）
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(memberRes.getMemberAccount(), null, Collections.emptyList());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        MemberLoginResultDTO result = new MemberLoginResultDTO();
        result.setMember(memberRes);
        result.setToken(token);

        return BaseResult.ok(result);
    }


    @PostMapping("/MemberLogout")
    public BaseResult<String> memberLogout(HttpServletRequest request) {
        // 1. 从请求头中提取 token
        String authHeader = request.getHeader("Authorization");

        if (authHeader == null ) {
            return BaseResult.error(CodeEnum.UNAUTHORIZED); // 可以定义一个401枚举
        }

        // 2. 可选：将 token 放入 Redis 黑名单，设置过期时间与 token 保持一致（仅在你启用了黑名单机制时）
        // redisTemplate.opsForValue().set("blacklist:" + token, "true", token有效时间, TimeUnit.SECONDS);

        // 3. 返回退出成功
        return BaseResult.ok("退出成功");
    }


}
